Mamba pytorch复现

Mamba pytorch复现

​ 代码思路是:MambaBlock -> ResidualBlock -> Mamba

​ 其中MambaBlock就是最基础的单个Mamba块,如下图最左侧的部分:18

​ ResidualBlock就是Mamba块加上Normalize和残差连接的块,Mamba就是多个ResidualBlock叠加起来,再加上LLM最基本的Embedding等组成的LLM

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
"""
Glossary:
b: batch size (`B` in Mamba paper [1] Algorithm 2)
l: sequence length (`L` in [1] Algorithm 2)
d or d_model: hidden dim
n or d_state: latent state dim (`N` in [1] Algorithm 2)
expand: expansion factor (`E` in [1] Section 3.4)
d_in or d_inner: d * expand (`D` in [1] Algorithm 2)
A, B, C, D: state space parameters (See any state space representation formula)
(B, C are input-dependent (aka selective, a key innovation in Mamba); A, D are not)
Δ or delta: input-dependent step size
dt_rank: rank of Δ (See [1] Section 3.6 "Parameterization of ∆")
"""


import math
import json
from typing import Union
import torch
import torch.nn as nn
import torch.nn.functional as F
import einops
from dataclasses import dataclass

@dataclass
class ModelArgs:
d_model: int
n_layer: int
vocab_size: int
d_state: int = 16
expand: int = 2
dt_rank: Union[int, str] = 'auto'
d_conv: int = 4
pad_vocab_size_multiple: int = 8
conv_bias: bool = True
bias: bool = False

def __post__init__(self):
self.d_inner = int(self.expand * self.d_model)

if self.dt_rank == 'auto':
self.dt_rank = math.ceil(self.d_model / 16)

if self.vocab_size % self.pad_vocab_size_multiple != 0:
self.vocab_size += (self.pad_vocab_size_multiple
- self.vocab_size % self.pad_vocab_size_multiple)


"""
MabmbaBlock是最基本的Mamba模块,他实现的就是单个的MambaBlock
"""
class MambaBlock(nn.Module):
def __init__(self, args: ModelArgs):
super().__init__()
self.args = args

self.linear1(args.d_inner, args.d_model, bias=args.bias)
self.linear2(args.d_inner, args.d_model, bias=args.bias)

self.conv1d = nn.Conv1d(
in_channels=args.d_inner,
out_channels=args.d_inner,
bias=args.conv_bias,
kernel_size=args.d_conv,
groups=args.d_inner,
padding=args.d_conv - 1
)

self.x2Delta = nn.Linear(args.d_inner, args.dt_rank, bias=False)
self.x2B = nn.Linear(args.d_inner, args.d_state, bias=False)
self.x2C = nn.Linear(args.d_inner, args.d_state, bias=False)

self.dt_proj = nn.Linear(args.dt_rank, args.d_inner, bias=False)

A = einops.repeat(torch.arange(1, args.d_state + 1), 'n -> d n', d=args.d_inner)
self.A_log = nn.Parameter(torch.log(A))
self.D = nn.Parameter(torch.ones(args.d_inner))
self.out_proj = nn.Linear(args.d_inner, args.d_model, bias=args.bias)


def forward(self, x):
(b, l, d) = x.shape
res = self.linear1(x)
x = self.linear2(x)

x = einops.rearrange(x, 'b l d_in -> b d_in l')
# x = self.conv1d(x)[:, :, :l]
x = self.conv1d(x)
x =einops.rearrange(x, 'b d_in l -> b l d_in')
x = F.silu(x)

y = self.ssm(x)
y = y * F.silu(res)
output = self.out_proj(y)
return output

def ssm(self, x):
(d_in ,n) = self.A_log.shape
A = - torch.exp(self.A_log.float())
D = self.D.float()

delta = self.x2Delta(x)
B = self.x2B(x)
C = self.x2C(x)
delta = F.softplus(self.dt_proj(delta))
y = self.selective_scan(x, delta, A, B, C, D)

return y

def selective_scan(self, x, delta, A, B, C, D):
(b, l, d_in) = x.shape
n = A.shape[1]
A_bar = torch.exp(einops.einsum(delta, A, 'b l d_in, d_in n -> b l d_in n'))
B_bar_x = einops.einsum(delta, B, x, 'b l d_in, b l n, b l d_in -> b l d_in n')


"""
下面这段没有用并行算法,实现起来也应该不复杂
我试着以后有时间实现一下
"""
h = torch.zeros((b, d_in, n), device=A_bar.device)
ys = []
for i in range(l):
h = A_bar[:, i] * h + B_bar_x[:, i]
y = einops.einsum(h, C[:, i, :], 'b d_in n, b n -> b d_in')
ys.append(y)

y = torch.stack(ys, dim=1)
y = y + x * D
return y


class ResidualBlock(nn.Module):
def __init__(self, args: ModelArgs):
"""Simple block wrapping Mamba block with normalization and residual connection."""
super().__init__()
self.args = args
self.mixer = MambaBlock(args)
self.norm = RMSNorm(args.d_model)

def forward(self, x):
output = self.mixer(self.norm(x)) + x
return output


"""
用多个Mamba块组成的模型
"""
class Mamba(nn.Module):
def __init__(self, args: ModelArgs):
super().__init__()
self.args = args

self.embedding = nn.Embedding(args.vocab_size, args.d_model)
self.layers = nn.ModuleList([ResidualBlock(args) for _ in range(args.n_layer)])
self.norm_f = RMSNorm(args.d_model)

self.lm_head = nn.Linear(args.d_model, args.vocab_size, bias=False)
self.lm_head.weight = self.embedding.weight # Tie output projection to embedding weights.
# See "Weight Tying" paper


def forward(self, input_ids):
x = self.embedding(input_ids)
for layer in self.layers:
x = layer(x)
x = self.norm_f(x)
logits = self.lm_head(x)
return logits


@staticmethod
def from_pretrained(pretrained_model_name: str):
"""
在huggingface的transformers库里找预训练好的模型

Args:
pretrained_model_name: One of
* 'state-spaces/mamba-2.8b-slimpj'
* 'state-spaces/mamba-2.8b'
* 'state-spaces/mamba-1.4b'
* 'state-spaces/mamba-790m'
* 'state-spaces/mamba-370m'
* 'state-spaces/mamba-130m'
Returns:
model: Mamba model with weights loaded

"""
from transformers.utils import WEIGHTS_NAME, CONFIG_NAME
from transformers.utils.hub import cached_file

def load_config_hf(model_name):
resolved_archive_file = cached_file(model_name, CONFIG_NAME,
_raise_exceptions_for_missing_entries=False)
return json.load(open(resolved_archive_file))


def load_state_dict_hf(model_name, device=None, dtype=None):
resolved_archive_file = cached_file(model_name, WEIGHTS_NAME,
_raise_exceptions_for_missing_entries=False)
return torch.load(resolved_archive_file, weights_only=True, map_location='cpu', mmap=True)

config_data = load_config_hf(pretrained_model_name)
args = ModelArgs(
d_model=config_data['d_model'],
n_layer=config_data['n_layer'],
vocab_size=config_data['vocab_size']
)
model = Mamba(args)

state_dict = load_state_dict_hf(pretrained_model_name)
new_state_dict = {}
for key in state_dict:
new_key = key.replace('backbone.', '')
new_state_dict[new_key] = state_dict[key]
model.load_state_dict(new_state_dict)

return model


class RMSNorm(nn.Module):
def __init__(self,
d_model: int,
eps: float = 1e-5):
super().__init__()
self.eps = eps
self.weight = nn.Parameter(torch.ones(d_model))

def forward(self, x):
output = x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps) * self.weight
return output


if __name__ == '__main__':
def generate(model,
tokenizer,
prompt: str,
n_tokens_to_gen: int = 50,
sample: bool = True,
top_k: int = 40):
model.eval()

input_ids = tokenizer(prompt, return_tensors='pt').input_ids

for token_n in range(n_tokens_to_gen):
with torch.no_grad():
indices_to_input = input_ids
next_token_logits = model(indices_to_input)[:, -1]

probs = F.softmax(next_token_logits, dim=-1)
(batch, vocab_size) = probs.shape

if top_k is not None:
(values, indices) = torch.topk(probs, k=top_k)
probs[probs < values[:, -1, None]] = 0
probs = probs / probs.sum(axis=1, keepdims=True)

if sample:
next_indices = torch.multinomial(probs, num_samples=1)
else:
next_indices = torch.argmax(probs, dim=-1)[:, None]

input_ids = torch.cat([input_ids, next_indices], dim=1)

output_completions = [tokenizer.decode(output.tolist()) for output in input_ids][0]
return output_completions

pretrained_model_name = 'state-spaces/mamba-370m'

from transformers import AutoTokenizer
model = Mamba.from_pretrained(pretrained_model_name)
tokenizer = AutoTokenizer.from_pretrained('EleutherAI/gpt-neox-20b')
print(generate(model, tokenizer, 'Mamba is the'))